<template>
<div id="login-view"  :style="backgourdDiv">
    <div id = "login-div">
        <div class="sign-font">Sgin in</div>

        <div class="register">
            <div class="register-left">
                <!-- No Account , click to sign  -->
                没有账号？click apple to sign
            </div>
            <el-button class="register-right" type="danger" @click="changeRegisterStatus">
                <img :src="registerIcon" class="apple">
            </el-button>
            
        </div>

        <div class="login-in">
            Username or Email: <br><br>
            <el-input v-model="usernameOrEmail" placeholder="请输入用户名"></el-input><br><br>
            Password: <br><br>
            <el-input v-model="password"  placeholder="请输入密码" show-password></el-input>
            <br><br>
            <el-button type="primary" class="login-btn" @click="login">login in</el-button >
        </div>
        
    </div>

    <transition name="el-zoom-in-center">
        <div id="register-div" v-if="registerIsShow">
            <div class="avater-div">
                <el-upload
                class="avatar-uploader"
                action
                :show-file-list="false"
                v-model="registerForm.avater"
                :before-upload="beforeAvatarUpload"
                :http-request="getImgPutUrlFromSts"
                >
                <img v-if="imageUrl" :src="imageUrl" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
            </div>

            <br>
            <div id="registerForm">
                <!-- :rules="registerRules" -->
                <el-form :model="registerForm" :rules="registerRules"  ref="registerForm" label-width="80px" >
                    <el-form-item label="姓名" prop="name">
                        <el-input v-model="registerForm.name" placeholder="请填写真实姓名"></el-input>
                    </el-form-item>

                    <el-form-item label="学号" prop="stuNumber">
                        <el-input v-model="registerForm.stuNumber" placeholder="请填写正确的学号"></el-input>
                    </el-form-item>

                    <el-form-item label="用户名" prop="username">
                        <el-input v-model="registerForm.username" placeholder="请填写登录用的用户名"></el-input>
                    </el-form-item>

                    <el-form-item label="密码" prop="password">
                        <el-input v-model="registerForm.password" show-password></el-input>
                    </el-form-item>
                    

                    <el-form-item label="手机号" prop="phone">
                        <el-input v-model="registerForm.phone" placeholder="请填写正确的手机号"></el-input>
                    </el-form-item>

                    <el-form-item label="邮箱" prop="email">
                        <el-input v-model="registerForm.email" placeholder="请正确填写邮箱格式"></el-input>
                    </el-form-item>

                    <el-form-item label="性别" prop="gender">
                           <el-radio-group v-model="registerForm.gender">
                                <el-radio label="男"></el-radio>
                                <el-radio label="女"></el-radio>
                            </el-radio-group>
                    </el-form-item>

                    <!-- <el-form-item label="班级" prop="belongClass">
                        <el-input v-model="registerForm.belongClass" placeholder="可以不填。请照此格式：3G软件1702"></el-input>
                    </el-form-item> -->




                    <el-form-item>
                        <el-button style="border-radius:8px" type="primary" @click="registerSubmit(registerForm)">立即创建</el-button>
                        <el-button style="border-radius:8px" @click="resetForm(registerForm)">重置</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </div>
    </transition>
</div>

</template>

<script>
// import axios from 'axios'
import * as FILEAPI from '../api/file/index'
import * as USERAPI from '../api/user/index'
import UUID from 'uuidjs';
import { Storage } from "../storage";
import Bus from '../utils/bus'

export default {
    data() {
        return {
            registerForm:{
                name:'',
                username:'',
                password:'',
                gender:'',
                email:'',
                phone:'',
                stuNumber:'',
                belongClass:'',
                avatar: '',
            },
            registerRules:{
                name:[ { required: true, message: '请输入姓名', trigger: 'blur' }],
                username:[ { required: true, message: '请输入用户名', trigger: 'blur' }],
                password:[ { required: true, message: '请输入密码', trigger: 'blur' }],
                email:[ { required: true, type:'email', message: '请输入正确的邮箱', trigger: 'blur' }],
                phone:[ { required: true, message: '请输入手机号', trigger: 'blur' }],
                stuNumber:[ { required: true, message: '请输入学号', trigger: 'blur' }],
                gender:[ { required: true, message: '请选择性别', trigger: 'blur' }],
            },
            registerIsShow: false,
            usernameOrEmail:'',
            password:'',
            backgourdDiv:{
                backgroundImage:'url(' + require('../../public/img/1.webp') + ')',
                backgroundRepeat:'no-repeat',
                backgroundSize:'cover',
                backgroundPosition: 'center',
            },
            registerIcon: require('../../public/img/apple.png'),
            dialogImageUrl: '',//预览url
            dialogVisibleImg:false,
            hideUpload:false,
            disabled:false,
            imageUrl:"",
        }
    },
    methods:{
        changeRegisterStatus() {
            if (this.registerIsShow) {
                this.registerIsShow = false
            } else {
                this.registerIsShow = true
            }
        },
        handleAvatarSuccess(res, file) {
            console.log(res,file)
            // this.imageUrl = require('../../public/img/apple.png')
        },
        beforeAvatarUpload(file) {
            console.log(file.type)
            const isJPG = file.type === 'image/jpeg';
            const isPNG = file.type === 'image/png';
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isJPG && !isPNG) {
                this.$message.error('上传头像图片只能是 JPG/PNG 格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!');
            }
            return (isJPG || isPNG) && isLt2M;
        },
        registerSubmit(form) {
            USERAPI.register(form).then(res => {
                if(res.code === 100) {
                    this.$message({
                        showClose: true,
                        message: res.data.error,
                        type: 'error'
                    });
                    return
                }
                let data = res.data
                //token有效期为24小时 24 * 60 * 60 * 1000
                Storage.set("nothing-token",data.token, 24 * 60 * 60 * 1000)
                Storage.set("stu", data.stu, 24 * 60 * 60 * 1000)
                Storage.set("isLogin", true, 24 * 60 * 60 * 1000)

                this.$message({
                        showClose: true,
                        message: "登录成功",
                        type: 'success'
                });

                this.$router.push(
                    {name:"Course"}
                )

                Bus.$emit("isLogin", true)
            })
            console.log(form)
        },
        resetForm(form) {
                form.name = ''
                form.username = ''
                form.password = ''
                form.gender = ''
                form.email = ''
                form.phone = ''
                form.stuNumber = ''
                form.belongClass = ''
                form.avatar = ''
        },
        login() {
            if(this.usernameOrEmail == '' || this.password == '') {
                this.$message({
                    showClose: true,
                    message: '账号密码都不能为空',
                    type: 'error'
                });
                return
            }
            let form = {
                password: this.password
            }
            let reg = /^([0-9A-Za-z\-_\.]+)@([0-9a-z]+\.[a-z]{2,3}(\.[a-z]{2})?)$/g
            let isEmail = reg.test(this.usernameOrEmail)
            if(isEmail) {
                form.email = this.usernameOrEmail
            }else {
                form.username = this.usernameOrEmail
            }

            USERAPI.login(form).then(res => {
                if(res.code === 100) {
                    this.$message({
                        showClose: true,
                        message: res.data.error,
                        type: 'error'
                    });
                    return
                }
                let data = res.data
                //token有效期为24小时 24 * 60 * 60 * 1000
                Storage.set("nothing-token",data.token, 24 * 60 * 60 * 1000)
                Storage.set("stu", data.stu, 24 * 60 * 60 * 1000)
                Storage.set("isLogin", true, 24 * 60 * 60 * 1000)

                this.$message({
                        showClose: true,
                        message: "登录成功",
                        type: 'success'
                });

                this.$router.push(
                    {name:"Course"}
                )

                Bus.$emit("isLogin", true)
                

            }).catch(err => {
                this.$message({
                    showClose: true,
                    message: '网络错误，或者服务器宕机, error:' +  err,
                    type: 'error'
                });
            })


        },
        getImgPutUrlFromSts(option) {
            let fileName = UUID.generate()
            // let fileName = 'avater7'
            let fileType = option.file.type.split("/")[1]
            FILEAPI.getImgUrl(fileName, fileType).then(res => {

                let url = res.data.URL

                const oReq = new XMLHttpRequest();
                oReq.open('PUT', url, true);
                oReq.setRequestHeader("Content-Type", "application/octet-stream")
                oReq.setRequestHeader("x-oss-meta-author", "nothing")
                oReq.send(option.file);
                oReq.onload = () => {
                    this.imageUrl = `https://nothing-link.oss-cn-beijing.aliyuncs.com/${fileName}.${fileType}`;
                    this.registerForm.avatar = `https://nothing-link.oss-cn-beijing.aliyuncs.com/${fileName}.${fileType}`;
                };
            }).catch((error) => {
                this.$notify.error({
                    title: '网路错误，或者服务器宕机',
                    message: error,
                });
            });
        }

    },
    mounted() {
        let isLogin = Storage.get("isLogin")
        if(isLogin != undefined && Boolean(isLogin) == true) {
            console.log("?")
            this.$router.push(
                    {name:"Course"}
                )
        }
    }

}
</script>

<style>

#login-view {
    width: 100%;
    height: 1000px;
    display: flex;
    /* justify-content: space-between; */
    /* 子元素 交叉轴居中布局 */
    align-items: center;
}

#login-div {
    font-size: 15px;
    margin-top: -15%;
    margin-left: 10%;
    width: 24rem;
    /* margin-left: 10%; */
    height: 34rem;       
    background-color:rgba(255,255,255,0.8);
    /* opacity: 0.8; */
    border-radius: 20px;
    display: flex;
    /* align-items: flex-start; */
    align-items: center;
    /* 交叉轴排放 */
    flex-direction: column;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.3);
}

/* register */
.register {
    height: 50px;
    widows: 250px;
    line-height: 40px;
    display: flex;
    flex: 0.2;
}

.register-left {
    padding-left: 6%;
    width: 235px;
    height: 40px;
    background-color: rgba(39, 43, 230, 0.8);
    border-radius: 10px;
    color: white;
}

.register-right {
    width: 40px;
    height: 40px;
    margin-left: 2%;
    background-color: rgba(255, 99, 71, 0.7);
    padding-left: 3.5%;
    padding-top: 3%;
    border-radius: 10px;
}

.apple {
    width: 20px;
    height: 20px;
}

.sign-font{
    margin-top: 15%;
    font-size: 55px;
    display: flex;
    flex: 0.3;
}

/* login */
.login-in {
    width: 270px;
    font-size: 14px;
    flex: 1;
}

.login-btn { 
    width: 120px;
    height: 45px;
    border-radius: 35px;
    background-image: linear-gradient(to right, #fa709a 0%, #fee140 100%);
}

#register-div {
    display: flex;
    /* 交叉轴排放 */
    flex-direction: column;
    width: 24rem;
    margin-left: 10%;
    margin-right: 10%;
    height: 43rem;       
    flex: 2;
    background-color:rgba(255,255,255,0.8);
    align-items: center;
    margin-top: -15%;

    border-radius: 20px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.3);
}

/* .hide .el-upload--picture-card {
    display: none;
} */



#registerForm {
    width: 350px;
    margin-right: 5%;
    /* padding-right: 4%; */
}


 .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    /* position: relative; */
    border-radius: 50%;
    margin-top: 5%;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #FED049;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #FED049;
    width: 100px;
    height: 100px;
    line-height: 100px;
    border-radius: 50%;
    text-align: center;
}
  
.avatar {
    width: 100px;
    height: 100px;
    border-radius: 50%;
    display: block;
}

.avatar:hover {
    opacity: 0.4;
}



</style>